import * as Cesium from "cesium";

/**
 * 坐标转化
 */
export default class CesiumCrood {
  constructor(viewer, ellipsoid) {
    this.viewer = viewer;
    this.ellipsoid = ellipsoid || Cesium.Ellipsoid.WGS84;
  }
  /**
   *
   * @param { 屏幕坐标 } screenPosition
   * @returns { 笛卡尔坐标  Cartesian3 }
   */
  ScreenToCartesian3(screenPosition) {
    const scene = this.viewer.scene;
    const ray = this.viewer.camera.getPickRay(screenPosition); // 射线模型
    const cartesian = scene.globe.pick(ray, scene); // 世界坐标
    return cartesian;
  }
  /**
   * 笛卡尔坐标转经纬度
   * @param {* 笛卡尔坐标 } cartesian3
   * @returns { 经纬度坐标数组 }
   */
  cartesian3ToLonLatHeight(cartesian, precision = 6) {
    const geo = this.ellipsoid.cartesianToCartographic(cartesian);
    // 方式2: 将 Cartesian3 转换为 Cartographic (经纬度坐标)
    // const geo = Cesium.Cartographic.fromCartesian(cartesian);
    const longitude = parseFloat(
      Cesium.Math.toDegrees(geo.longitude).toFixed(precision)
    );
    const latitude = parseFloat(
      Cesium.Math.toDegrees(geo.latitude).toFixed(precision)
    );
    const height = parseFloat(
      Cesium.Math.toDegrees(geo.height).toFixed(precision)
    );
    return [longitude, latitude, height];
  }
  /**
   * 笛卡尔坐标转经纬度
   * @param {* 笛卡尔坐标数组 cartesian3[] }
   * @returns { 经纬度坐标数组（二维数组）  }
   */
  cartesian3ToLonLatHeightArray(cartesianList, precision = 6) {
    const list = cartesianList.map((cartesian) =>
      this.cartesian3ToLonLatHeight(cartesian, precision)
    );
    return list;
  }
  /**
   * 矩形坐标 转 四个顶点的经纬度坐标
   * @param { 矩形坐标 Rectangle} rectangle
   * @returns { 经纬度坐标数组 }
   */
  rectangleToLatLon(rectangle) {
    // 将矩形的四个顶点从弧度转换为度数
    const west = Cesium.Math.toDegrees(rectangle.west); // 西经
    const south = Cesium.Math.toDegrees(rectangle.south); // 南纬
    const east = Cesium.Math.toDegrees(rectangle.east); // 东经
    const north = Cesium.Math.toDegrees(rectangle.north); // 北纬
    // 四个顶点的经纬度   这个顺序是要固定的
    return [
      [west, north],
      [east, north],
      [east, south],
      [west, south],
    ];
  }
}
